package com.mall.controller;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.entity.*;
import com.mall.pojo.OrderVo;
import com.mall.pojo.ResponseMessage;
import com.mall.service.*;
import com.mall.util.DateUtils;
import com.mall.util.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ShouPeng
 * @since 2023-04-17
 */
@RestController
@RequestMapping("/user/order")
@CrossOrigin
@Slf4j
public class OrderController {
    @Autowired
    UserService userService;

    @Autowired
    IUserCouponService userCouponService;

    @Autowired
    ICouponService couponService;

    @Autowired
    IUserAddressService addressService;
    @Autowired
    ILogisticsCompanyService logisticsCompanyService;

    @Autowired
    IOrderService orderService;
    @Autowired
    IShoppingCartService shoppingCartService;

    @PostMapping
    public ResponseMessage submitOrder(@RequestBody OrderVo order, HttpServletRequest request) throws ParseException {
        Order newOrder = new Order();
        newOrder.setOrderNo(String.valueOf(System.currentTimeMillis()));
        newOrder.setExtraInfo(order.getExtraInfo());
        String userId = UserUtils.userId(request);
        newOrder.setUserId(userId);
        if (ObjectUtils.isEmpty(order.getShoppingCartIds())){
            return ResponseMessage.custom("-1","请选择结算商品...");
        }
        List<ShoppingCart> cartItems = shoppingCartService.queryShoppingCartByCartIds(
                userId,
                order.getShoppingCartIds()
                );
        if (cartItems.isEmpty()){
            return ResponseMessage.custom("-1","你的购物车空空如也哦~");
        }
        double totalPrice = 0;
        LogisticsCompany company = logisticsCompanyService.queryLogisticsCompanyById(order.getCompanyId());
        newOrder.setLogisticsCompany(company.getCompanyName());
        newOrder.setLogisticsPrice(company.getPrice());
        totalPrice += company.getPrice();

        newOrder.setLogisticsAddress(order.getLogisticsAddress());
        List<OrderItem> items = new ArrayList<>();
        for (ShoppingCart item : cartItems) {
            totalPrice += item.getGoodsCount() * item.getGoodsPrice();
            items.add(new OrderItem(null,null,item.getGoodsId(),item.getGoodsCount(), String.valueOf(item.getShoppingCartId())));
        }

        //使用优惠券
        if (order.getCouponId() != -1){
            UserCoupon userCoupon = userCouponService.queryCouponById(userId,order.getCouponId());
            Coupon coupon = couponService.queryCouponById(order.getCouponId());
            if (coupon.getCouponThreshold() <= totalPrice
                    && !userCoupon.getCouponStatus()
                    && DateUtils.strToDate(userCoupon.getCouponExpireTime()).getTime() >= System.currentTimeMillis()){
                totalPrice -= coupon.getCouponValue();
                newOrder.setCouponId(String.valueOf(coupon.getCouponId()));
            }
        }

        newOrder.setTotalPrice(totalPrice);

        try {
            orderService.addOrder(newOrder,items);
            return ResponseMessage.success(newOrder.getOrderId());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseMessage.custom("-1","添加订单失败，请稍后再试~");
        }

    }


    @GetMapping
    public ResponseMessage queryOrderById(@RequestParam String orderId,HttpServletRequest request){
        return ResponseMessage.success(orderService.queryOrderById(UserUtils.userId(request),orderId));
    }

    /**
     * 根据订单号查询订单
     * @param orderNo
     * @return
     */
    @GetMapping("/orderNo")
    public ResponseMessage queryOrderByOrderNo(@RequestParam String orderNo){
        return ResponseMessage.success(orderService.selectByOrderNo(orderNo));
    }

    //获取我的全部订单
    @GetMapping("/list")
    public ResponseMessage queryOrderById(@RequestParam(defaultValue = "15") Integer pageSize,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 HttpServletRequest request){
        return ResponseMessage.success(orderService.queryOrder(new Page<Order>(page,pageSize),UserUtils.userId(request)));
    }


    @PutMapping
    public ResponseMessage cancelOrder(@RequestParam String orderId,HttpServletRequest request){
        return orderService.setOrderStatus(orderId,UserUtils.userId(request),0,null)
                ? ResponseMessage.success()
                : ResponseMessage.custom("-1","取消订单失败,订单ID：" + orderId);
    }

    @PutMapping("/pay")
    public ResponseMessage payOrder(@RequestParam String orderId,@RequestParam Integer payType,HttpServletRequest request){
        //使用零钱支付
        String userId = UserUtils.userId(request);

        if (orderService.setOrderStatus(orderId, userId,2,payType)) {
            return ResponseMessage.success();
        }
        return ResponseMessage.custom("-1","支付失败,订单ID：" + orderId);
    }

    /**
     * 确认收货
     */
    @PutMapping("/confirm")
    public ResponseMessage confirmOrder(@RequestParam String orderId,HttpServletRequest request){
        String userId = UserUtils.userId(request);
        if (orderService.setOrderStatus(orderId, userId,5,null)) {
            return ResponseMessage.success();
        }
        return ResponseMessage.custom("-1","确认收货失败,订单ID：" + orderId);
    }

    @DeleteMapping
    public ResponseMessage deleteOrder(@RequestBody List<String> ids){
        orderService.deleteOrder(ids);
        return ResponseMessage.success();
    }

}

